<?php
/**
 * Author: yixuan
 * Desc: mobile控制器基类
 * Time: 2016/5/27 11:20
 */

namespace app\mobile\controller;

use app\lib\WxoffiAccount;
use app\model\Comm;
use app\model\Fans;
use app\model\Scan;
use app\model\Poster;
use app\model\Theme;
use app\model\Worker;
use app\model\Common;
use app\model\Relation;
use think\Controller;
use think\Session;

class Base extends Controller
{

    public function __construct()
    {
        global $_G, $_P;
        $h5_not_auth_list = array(
            'excel',
            'qr',
            'wdaping',
            'daping',
            'wdapinglingze',
            'wdapinglingze',
            'llsmscallback',
        );

        if (!empty($_P['m']) && !empty($_P['fromuid'])) {
            if (!empty($_G['theme']['blacklist'])) {
                if (strstr($_G['theme']['blacklist'] . "|", "|" . $_P['fromuid'] . "|") !== false) {
                    $txt = !empty($_G['theme']['mobile']) ? '<br><br>咨询电话：' . $_G['theme']['mobile'] : '';
                    echo '<title>活动暂停</title><H1>活动暂停，给您带来的不便还望凉解；' . $txt . '</H1>';
                    exit;
                }
            }
        }

        if (!empty($_G['system']['tiaozhuanurl']) && strstr($_G['system']['tiaozhuanurl'], "跳转至") == false) {
            echo "<script language='javascript' type='text/javascript'>";
            echo "window.location.href='{$_G['system']['tiaozhuanurl']}';";
            echo "</script>";
            exit;
        }

        //判断微信服务器
        if (1 == 1) {
            $WechatServerIP = "跟https,113.96.219.105,113.96.221.178,113.96.223.239,113.96.223.240,202.127.28.204,58.251.98.105,61.129.11.211,61.151.178.150,61.151.182.110,61.151.179.84,61.151.207.141,61.129.7.236,101.89.239.232,101.227.139.171,101.227.139.173,101.89.29.78,101.91.60.107,116.228.100.202,180.163.220.5,223.104.210.139,61.129.6.151,61.129.6.225,61.151.178.197,61.151.178.236,113.96.223.176,58.251.98.100,119.123.30.160,61.151.178.175,27.115.124.6,27.115.124.70,61.151.207.205,,跟http,113.31.115.156,47.92.103.177,47.92.132.229,47.92.29.149,110.80.135.12,113.96.232.116,113.96.232.117,113.96.232.118,113.96.232.119,59.36.121.170,59.36.121.171,59.36.121.172,59.36.121.173,59.36.121.174,59.36.121.175,59.36.121.176,59.36.121.178,111.7.100.16,111.7.100.17,111.7.100.18,111.7.100.19,111.7.100.20,111.7.100.21,111.7.100.22,111.7.100.23,111.7.100.24,111.7.100.25,111.7.100.26,111.7.100.27,36.99.136.130,36.99.136.131,36.99.136.132,36.99.136.134,36.99.136.138,36.99.136.139,36.99.136.140,36.99.136.141,36.99.136.142,36.99.136.143,42.236.10.114,42.236.10.117,42.236.10.125,42.236.10.75,42.236.10.78,42.236.10.84,42.236.10.93,111.177.18.237,113.57.147.211,61.183.201.26,222.240.44.115,36.158.194.201,221.130.3.140,101.132.101.201,101.132.102.65,101.132.106.111,101.132.114.193,101.132.143.18,101.132.149.250,101.132.154.84,101.132.159.74,101.132.169.97,101.132.190.92,101.132.193.36,101.132.37.16,101.132.64.85,101.132.73.61,101.91.60.109,106.14.11.104,106.14.114.244,106.14.115.254,106.14.152.41,106.14.167.211,106.14.195.175,106.15.181.202,106.15.191.19,106.15.191.82,106.15.224.49,180.163.220.3,180.163.220.4,180.163.220.66,180.163.220.67,180.163.220.68,47.100.100.21,47.100.108.86,47.100.110.234,47.100.17.89,47.100.174.179,47.100.194.160,47.100.207.141,47.100.216.244,47.100.223.123,47.100.239.179,47.100.27.168,47.100.7.25,47.101.132.237,47.101.137.148,47.101.149.80,47.101.150.85,47.101.152.108,47.101.159.166,47.101.178.254,47.101.184.89,47.101.186.75,47.101.187.254,47.101.192.187,47.101.192.218,47.101.192.220,47.101.195.83,47.101.196.170,47.101.196.225,47.101.196.50,47.101.198.126,47.101.198.3,47.101.198.80,47.101.199.232,47.101.200.112,47.101.200.12,47.101.200.206,47.101.200.71,47.101.201.149,47.101.201.176,47.101.201.183,47.101.201.186,47.101.202.135,47.101.202.208,47.101.202.32,47.101.202.55,47.101.32.174,47.101.34.114,47.101.40.28,47.101.46.78,47.101.49.229,47.101.53.251,47.101.55.35,47.101.60.78,47.103.14.133,47.103.22.107,61.129.6.227,61.151.178.166,61.151.178.174,61.151.182.102,61.151.182.103,61.151.182.104,61.151.182.105,61.151.182.106,61.151.182.107,61.151.182.108,61.151.182.109,61.151.182.11,61.151.182.110,61.151.182.111,61.151.182.112,61.151.182.115,61.151.182.116,61.151.182.117,61.151.182.118,61.151.206.125,61.151.206.126,61.151.206.13,61.151.206.14,61.151.206.15,61.151.206.16,61.151.206.17,61.151.206.18,61.151.206.24,61.151.206.25,61.151.206.26,61.151.206.27,61.151.207.111,61.151.207.112,61.151.207.113,61.151.207.114,150.109.109.160,150.109.53.202,150.109.62.77,203.205.219.188,203.205.219.189,203.205.219.190,116.62.112.111,139.224.114.201,139.224.238.50,183.158.121.34,47.98.104.99,47.98.105.83,47.99.222.158,119.84.150.100,119.84.150.101,129.226.131.6,,支付回调IP,101.226.103.15,101.226.103.14,101.226.103.24,101.226.103.16,140.207.54.75,140.207.54.74,140.207.54.73,140.207.54.76,183.3.234.60,183.3.234.54,183.3.234.57,183.3.234.52,183.3.234.50,183.3.234.44,58.251.80.47,58.251.80.51,58.251.80.54,58.251.80.63,58.251.80.57,183.3.234.61,58.251.80.49,183.3.234.63,58.251.80.46,58.251.80.53,183.3.234.48,183.3.234.46,183.3.234.47,183.3.234.51,58.251.80.44,58.251.80.52,58.251.80.56,183.3.234.45,183.3.234.58,58.251.80.45,58.251.80.50,58.251.80.59,58.251.80.62,183.3.234.53,183.3.234.49,183.3.234.55,183.3.234.56,183.3.234.59,58.251.80.58,58.251.80.60,183.3.234.62,58.251.80.48,,电脑访问后台,183.39.175.177,223.104.63.188,101.89.239.238,14.103.6.253,101.91.60.110,101.227.139.163,101.227.139.172,101.227.139.178,101.89.239.120,101.91.60.104,101.91.62.11,101.91.62.65,14.30.0.98,223.104.64.212,58.247.206.145,58.247.206.150,59.36.119.227,61.129.6.174,61.129.6.203,61.129.7.235,61.151.178.165,,,,,,中国信通控股,117.50.33.2,117.50.33.3,117.50.33.5,117.50.33.8,117.50.81.130,117.50.81.132,117.50.81.133,117.50.81.137,117.50.81.134,117.50.81.135,117.50.81.140,119.177.180.150";
            if (stripos($WechatServerIP, $_G['clientip']) !== false && $_P['isqr'] != 1 && $_P['do'] == 'index') {
                if (DOMAIN0 == '17.yixuan.net' || DOMAIN0 == '20.xjpf.net' || DOMAIN0 == '50.yixuan.net' || DOMAIN0 == '60.yixuan.net') {
                    $isduijie = true;
                } else {
                    $isduijie = false;
                }
                if ($isduijie || $_SERVER['SERVER_PORT'] == 443 || (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) != 'off') || strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'https' || strtolower($_SERVER['HTTP_X_CLIENT_SCHEME']) == 'https') {
                    //https显示二维码
                    $inputurl = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?isqr=1&' . $_SERVER['QUERY_STRING'];
                    $QRURLNEW = "http://" . $_SERVER['HTTP_HOST'] . '/' . $_P['m'] . '/' . $_P['mpid'] . '/0/0/qr.aspx?isqr=1&url=';
                    $inputurlqr = $QRURLNEW . urlencode($inputurl);
                    die("<!DOCTYPE html>
                        <html>
                            <head>
                                <meta name='viewport' content='width=device-width, initial-scale=1, user-scalable=0'>
                                <title>请用微信访问</title><meta charset='utf-8'><meta name='viewport' content='width=device-width, initial-scale=1, user-scalable=0'><link rel='stylesheet' type='text/css' href='https://res.wx.qq.com/connect/zh_CN/htmledition/style/wap_err1a9853.css'>
                            </head>
                            <body>
                            <div class='page_msg'><div class='inner'><span class='msg_icon_wrp'><a style='color:#000;text-decoration: none;' href='{$inputurl}'><img style='padding:20px; width:200px;' src='{$inputurlqr}'></span><div class='msg_content'><h4>请在微信客户端打开</h4></div></a></div></div>
                            </body>
                        </html>");
                } else {
                    //跳转至https
                    $inputurl = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING'];
                    echo "<script language='javascript' type='text/javascript'>";
                    echo "window.location.href='$inputurl';";
                    echo "</script>";
                }
                exit;
            }


            $_G['system']['s']['pbsoftblank'] = "," . $_G['system']['s']['pbsoftblank'];
            $_G['IsWeixin'] = 0;

            //判断是否为同城检查员
            $_G['ISweixinip'] = stripos($_G['system']['s']['weixinxip'], $_G['clientip']);
            $_G['IsFansStatus4'] = false;
            if (!empty($_P['m'])) {
                if ($_G['address']['province'] == '广东' && !empty($_P['fromuid']) && !empty($_P['fopenid']) && $_P['scanqr'] != 'yx' && stripos($_G['system']['s']['pbsoftblank'], substr($_P['m'], -5)) == false && DOMAIN0 != "30.yixuan.net" && $_G['ISweixinip'] == false) {
                    //判断活动地区及白名单
                    if (stripos($_G['config']['whiteiplist'], $_G['clientip']) == false && $_G['config']['province'] != '广东省') {
                        //判断城市
                        if (empty($_G['address']['city']) || $_G['address']['city'] == '广州市' || $_G['address']['city'] == '深圳市' || $_G['address']['city'] == '东莞市') {
                            if ($_G['address']['province'] == '广东') {
                                if (empty($_G['address']['city']) || $_G['address']['city'] == '广州市' || $_G['address']['city'] == '深圳市' || $_G['address']['city'] == '东莞市') {
                                    $_G['IsFansStatus4'] = true;
                                }
                            }
                        }
                    }

                }
            }
        }
        if ($_P['isqr'] == 1) {
            $_G['IsFansStatus4'] = true;
        }
        //**地区显示特定内容
        if ($_P['do'] == 'index' && $_G['ISweixinip'] == false && $_G['IsFansStatus4'] == false && stripos($_G['system']['s']['pbsoftblank'], substr($_P['m'], -5)) == false && !empty($_P['m'])) {
            if ($_G['system']['s']['pbcity'] != "" || $_G['system']['s']['pbwxcity'] != "") {
                $city = $_G['address']['city'];
                $province = $_G['address']['province'];
                if (empty($city)) {
                    $city = "未知";
                }
                if (empty($province)) {
                    $province = "未知";
                }
                if ($_G['system']['s']['pbwxcity'] != "") {
                    if (stripos($_G['system']['s']['pbwxcity'], $city) !== false || stripos($_G['system']['s']['pbwxcity'], $province) !== false) {
                        if (empty($_G['system']['s']['pbcontent'])) {
                            $_G['IsWeixin'] = 1;
                        } else {
                            echo $_G['system']['s']['pbcontent'];
                            exit;
                        }
                    }
                }
                if ($_G['system']['s']['pbwxcity'] != "") {
                    if (stripos($_G['system']['s']['pbcity'], $city) !== false || stripos($_G['system']['s']['pbcity'], $province) !== false) {
                        echo "<script language='javascript' type='text/javascript'>";
                        echo "window.location.href='" . $_G['system']['s']['errorpage'] . "';";
                        echo "</script>";
                        exit;
                    }
                }
            }
        }
        $xuni_touxiang = OLD_SERVER == true || in_array(strtolower($_P['do']), $h5_not_auth_list) ? true : false;
        if (!$xuni_touxiang) {
            if ($_G['ISweixinip'] == false && $_G['IsFansStatus4'] == false && $_G['IsWeixin'] == 0 && $_SERVER['HTTP_HOST'] != $_G['system']['s']['domain1']) {
                if ($_G['system']['s']['domain1'] != "www.yixuan.net" && DOMAIN0 != "19.yixuan.net") {
                    $string = DOMAIN_YIXUAN . ',' . DOMAIN0 . ',' . $_G['system']['s']['domain2'] . "," . $_G['system']['s']['domain3'] . "," . $_G['system']['s']['domain5'] . "," . $_G['system']['s']['domain6'] . "," . $_G['system']['s']['domainsq'] . "," . $_G['system']['s']['domainfx'] . "," . $_G['system']['s']['domainyg'] . "," . $_G['system']['s']['domainsqby'] . "," . $_G['system']['s']['domainfxby'];
                    if (strstr($string, $_SERVER['HTTP_HOST']) !== false) {
                        $url = $_SERVER['REQUEST_URI'];
                        $url = $_G['url_scheme'] . $_G['system']['s']['domain1'] . $url;
                        echo "<script language='javascript' type='text/javascript'>";
                        echo "window.location.href='$url';";
                        echo "</script>";
                        exit;

                        //刷新备用页面 暂时停用
//                        $time120 =time()-120;
//                        $timehour = strtotime(date('Y-m-d H:00:00'));
//                        pdo_query("UPDATE ".tablename("00domain" )." SET count = 0 WHERE counttime < ".$timehour );
//
//                        //一天一换软件编号
//                        $timehour = strtotime(date('Y-m-d 00:00:00'));
//                        pdo_query("UPDATE ".tablename("00domain" )." SET count = 0, notes=null WHERE counttime < ".$timehour );
//                        if (date('i')<30){
//                            $subdomain = $_P['m'] ."1";
//                        }else{
//                            $subdomain = $_P['m'] ."2";
//                        }
//
//                        $sql = "SELECT * FROM " . tablename ( "00domain" ) . " where notes = '" . $subdomain ."'";
//                        $list = pdo_fetch ( $sql);
//                        if (empty($list)) {
//                            $sql = "SELECT * FROM " . tablename ( "00domain" ) . " where state=1 and notes is null and count<maxcount and addtime > " . $time120;
//                            $list = pdo_fetchall ( $sql);
//                            if (!empty($list)) {
//                                $list=$list[array_rand($list,1)];
//                            }
//                        }else{
//                            if (!($list['state']==1 && $list['count']<$list['maxcount'] && $list['addtime'] >  $time120)) {
//                                $list = array();
//                            }
//                        }
//                        if (!empty($list) && stripos($_G['system']['s']['pbsoftblank'],substr($_P['m'],-5))==false && !empty($_P['m']) && $_P['do']=='index') {
//                            //以下地区不进行跳转
//                            if (stripos( $_G['address']['area'],"广东")!==false || stripos($_G['address']['area'],"北")!==false || stripos($_G['address']['area'],"郑州")!==false || stripos($_G['address']['area'],"上海")!==false || stripos($_G['address']['area'],"腾讯")!==false  || stripos($_G['address']['area'],"机房")!==false ){
//                                echo "<script language='javascript' type='text/javascript'>";
//                                echo "window.location.href='$url';";
//                                echo "</script>";
//                                exit;
//                            }
//
//                            $domain=$list;
//                            pdo_query("UPDATE ".tablename("00domain" )." SET notes = '" .$subdomain . "' ,count = count+1,counttime =". time() ." WHERE id = ".$domain['id'] );
//                            $url = $url."&t=".time();
//                            $gourl = $url;
//                            $url = str_replace("?", "wenhao", $url);
//                            //链接加密
//                            $txt = $url;
//                            $key = $_P['m'];
//                            $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+";
//                            $nh = rand(0,60);
//                            $ch = $chars[$nh];
//                            $mdKey = md5($key.$ch);
//                            $mdKey = substr($mdKey,$nh%8, $nh%8+7);
//                            $txt = base64_encode($txt);
//                            $tmp = '';
//                            $i=0;$j=0;$k = 0;
//                            for ($i=0; $i<strlen($txt); $i++) {
//                                $k = $k == strlen($mdKey) ? 0 : $k;
//                                $j = ($nh+strpos($chars,$txt[$i])+ord($mdKey[$k++]))%64;
//                                $tmp .= $chars[$j];
//                            }
//                            $temptxt = urlencode($ch.$tmp);
//
//                            //解密看是否一致
//                            $key = $_P['m'];
//                            $txt = urldecode($temptxt);
//                            $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+";
//                            $ch = $txt[0];
//                            $nh = strpos($chars,$ch);
//                            $mdKey = md5($key.$ch);
//                            $mdKey = substr($mdKey,$nh%8, $nh%8+7);
//                            $txt = substr($txt,1);
//                            $tmp = '';
//                            $i=0;$j=0; $k = 0;
//                            for ($i=0; $i<strlen($txt); $i++) {
//                                $k = $k == strlen($mdKey) ? 0 : $k;
//                                $j = strpos($chars,$txt[$i])-$nh - ord($mdKey[$k++]);
//                                while ($j<0) $j+=64;
//                                $tmp .= $chars[$j];
//                            }
//                            $urlnew = base64_decode($tmp);
//
//                            if($url == $urlnew){
//                                $timetemp = time()+1234567890;
//                                $gourl = "http://" . $_P['m'] . "." . $domain['name'] . "/".intval($_P['mpid'])."/".intval($_P['themeid'])."/".intval($_P['fromuid'])."/".$_P['do'].".aspx?token=" .$temptxt."&t=".$timetemp;
//                            }
//                            echo "<script language='javascript' type='text/javascript'>";
//                            echo "window.location.href='" . $gourl ."';";
//                            echo "</script>";
//
//                        }else{
//                            echo "<script language='javascript' type='text/javascript'>";
//                            echo "window.location.href='$url';";
//                            echo "</script>";
//                        }
//                        exit;
                    }
                }
            }
            //客户公众号
            if ($_G['system']['gongzhong'] == 1 && $_G['IsWeixin'] == 0 && !$xuni_touxiang) {
                $string = "," . DOMAIN0 . "," . $_G['system']['domainhead3'] . "," . $_G['system']['domainhead4'];
                if (strstr($string, $_SERVER['HTTP_HOST']) !== false) {
                    $url = $_SERVER['REQUEST_URI'];
                    if (!empty($_G['system']['domainhead2'])) {
                        if (rand(0, 10) < 5) {
                            $url = $_G['url_scheme'] . $_G['system']['domainhead1'] . $url;
                        } else {
                            $url = $_G['url_scheme'] . $_G['system']['domainhead2'] . $url;
                        }
                    } else {
                        $url = $_G['url_scheme'] . $_G['system']['domainhead1'] . $url;
                    }
                    echo "<script language='javascript' type='text/javascript'>";
                    echo "window.location.href='$url';";
                    echo "</script>";
                    exit;
                }
            }
        }
        //疑似地区不进行授权
        if (!empty($_P['m']) && stripos($_G['config']['whiteiplist'], $_G['clientip']) == false) {
            $isweixinip = $_G['system']['s']['isweixinxserver'] == 1 && stripos($_G['system']['s']['weixinxip'], CLIENT_IP) !== false ? true : false;

            if (!stripos($_G['system']['s']['pbsoftblank'], substr($_P['m'], -5)) && !$isweixinip || $xuni_touxiang) {
                if ($xuni_touxiang || ($isweixinip || $_G['IsFansStatus4'])) {
                    $_G['openid'] = Session::get('openid');
                    $_G['uid'] = $_G['member']['uid'] = Session::get('uid');
                    if (empty($_G['openid'])) {
                        $_G['openid'] = 'vu_' . random(29);
                        Session::set('openid', $_G['openid']);
                        $_G['uid'] = $_G['member']['uid'] = -date("dHi");
                        Session::set('uid', $_G['uid']);
                    }
                }
            }
        }

        //去除ServerConfig无用参数
        foreach ($_G['system']['s'] as $key => $value) {
            if (substr($key, -4) == '_old') {
                unset($_G['system']['s'][$key]);
            }
            if (in_array($key, ['weixinxip', 'softtag0', 'softtag1', 'softtag2', 'adkeyword', 'whitelist', 'wxname1', 'wxname2', 'pbsoftblank', 'access_key_id', 'access_key_secret', 'in_point', 'out_point', 'edititem', 'yixuancert', 'yixuancertxcx', 'yixuankey2xcx', 'yixuancert2xcx'])) {
                unset($_G['system']['s'][$key]);
            }
        }


//        $tmp_openid = 'oio3S5unHMnkyc_UbeNVMJ9QIoG4';
//        //todo 处理用户本地登录态存储
        if (empty($_G['openid'])) {
            $tmp_openid = Session::get('openid');
            if (!empty($tmp_openid)) {
                $member_res = $this->checkMemberInfo($tmp_openid);
            }
            if (!$tmp_openid || empty($member_res)) {
                //跟据传入参数判断是访问 首页或员工注册
                $visit_page = $_G['url_full'];
                //设置跳转前路由
                Session::set('auth_pre_page', $visit_page);
                $auth_url = createMobileUrl('auth', ['themeid' => $_P['themeid']], true);
                $format_jump_auth_url = WxoffiAccount::getInstance()->getAuthUrl($auth_url);
                return $this->redirect($format_jump_auth_url);
            }
            //静默授权完成未授权头像
//            if (!$_G['member']['is_auth']) {
//                $_G['member']['auth_url'] = fans::get_login_url($_G['system'], $_G['theme']);
//            }
        }
        $sub_page = in_array($_P['do'], ['getconfig', 'getbasebeilai', 'getbasefcpdd', 'getbasepdd', 'getopenredbag', 'getbaseyx2020']) ? true : false;
        if (strpos($_G['openid'], 'vu_') != 0 && !$sub_page) {
            //挂载全局 $_G['platform']['jssdkconfig']
            WxoffiAccount::getInstance();
        }
    }

    /**
     * Desc: member信息查询或更新
     * Author: yixuan
     * Time: 2016/7/2 22:12
     * @param $user_access_token
     * @param $state
     * @return array|\Closure|\PDOStatement|string|\think\db\Query|\think\Model|void
     */
    protected function checkMemberInfo($user_access_token_or_openid, $state = '')
    {
        global $_G;
        if ($user_access_token_or_openid && $state) {
            //通过user_access_token 跟state查询member信息
            $user_access_token = $user_access_token_or_openid;
            //挂载全局openid
            if ($user_access_token['openid']) {
                $_G['openid'] = $user_access_token['openid'];
            }
            //判断state是否为YXSTATEPOP
            if ($state == 'YXSTATEPOP') {
                //拉取用户信息
                $user_info = WxoffiAccount::getInstance()->getUserInfo($user_access_token['access_token'], $user_access_token['openid']);
                if (!isset($user_info['errcode']) && $user_info['headimgurl'] && $user_info['nickname']) {
                    //更新member表信息
                    $user_avatar = $user_info['headimgurl'];
                    $user_nickname = $user_info['nickname'];
                }
            }
            //todo 查询member表是否存在记录
            $member_res = member_info($user_access_token['openid']);
            if (empty($member_res)) {
                $user_avatar = 'http://css2020.yixuan.net/2020css/yx2020/images/question.png';
                $user_nickname = '微信用户';
                $insert_data = [
                    'mpid' => $_G['mpid'],
                    'openid' => $user_access_token['openid'],
                    'unionid' => '',
                    'nickname' => $user_nickname,
                    'avatar' => $user_avatar,
                    'realname' => '',
                    'mobile' => '',
                    'updatetime' => time()
                ];
                $insert_res = member_save($insert_data);
                $insert_data['uid'] = $insert_res['uid'];
                $insert_data['is_auth'] = 0;
                unset($insert_data['unionid']);
                //挂载全局member
                $_G['member'] = $insert_data;
                //挂载全局uid
                $_G['uid'] = $insert_data['uid'];
                return $insert_data;
            } else if ($state == 'YXSTATEPOP') {
                $member_res['is_auth'] = 0;
                if ($user_avatar != 'http://css2020.yixuan.net/2020css/yx2020/images/question.png' && $user_nickname != '微信用户') {
                    //更新member表中的头像昵称
                    member_save(['nickname' => $user_nickname, 'avatar' => $user_avatar, 'updatetime' => time()], $user_access_token['openid']);
                    $member_res['nickname'] = $user_nickname;
                    $member_res['avatar'] = $user_avatar;
                }
                unset($member_res['unionid']);
                if ($member_res['nickname'] != '微信用户' && $member_res['avatar'] != 'http://css2020.yixuan.net/2020css/yx2020/images/question.png') {
                    $member_res['is_auth'] = 1;
                }
                //挂载全局member
                $_G['member'] = $member_res;
                //挂载全局uid
                $_G['uid'] = $member_res['uid'];
                return $member_res;
            }
        } else {
            //通过openid获取member信息
            $openid = $user_access_token_or_openid;
            //查询member信息是否存在
            $member_res = member_info($openid);
            if (empty($member_res)) {
                return [];
            }
            $member_res['is_auth'] = 0;
            unset($member_res['unionid']);
            if ($member_res['nickname'] != '微信用户' && $member_res['avatar'] != 'http://css2020.yixuan.net/2020css/yx2020/images/question.png') {
                $member_res['is_auth'] = 1;
            }
            $_G['openid'] = $openid;
            //挂载全局member
            $_G['member'] = $member_res;
            //挂载全局uid
            $_G['uid'] = $member_res['uid'];
            return $member_res;
        }
    }

    protected function checkuser()
    {
        global $_G, $_P;
        $themeid = intval($_P['themeid']);

        $is_clear_session = empty($_G['member']['uid']) && !empty($_G['openid']) ? true : false;
        $_G['member']['uid'] = Fans::getRealUid();
        $system = $_G['system'];
        if (empty($_G['member']['uid']) && $system['pn_wxapp'] > 0) {
            return;
        }
//        if ($_G['member']['uid'] == '3') {
//            $_G['member']['uid'] = 96;
//            $_G['openid'] = 'oYt5N1vJDUcNoueD0mY-gtMQcVE8';
//        }

        $workerid = intval($_P['workerid']);
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        $inputurl = $_G['url_full'];
        $inputurl = QRURLNEW . urlencode($inputurl);
        //检测链接是否为正常打开
        $theme = Theme::getById($themeid);
        $config = Theme::getConfig($themeid);
        if (!empty($theme['softkey'])) {
            if ($theme['softkey'] !== $_P['soft']) {
                return_msg('您访问的模块不存在，请重新进入');
            }
        }
        if (!empty($theme['blacklist'])) {
            if (!empty(intval($_P['fromuid']))) {
                if (strstr($theme['blacklist'] . "|", "|" . $_P['fromuid'] . "|") !== false) {
                    $txt = !empty($theme['mobile']) ? '<br><br>咨询电话：' . $theme['mobile'] : '';
                    echo '<title>活动暂停</title><H1>活动暂停，给您带来的不便还望凉解；' . $txt . '</H1>';
                    exit;
                }
            }
        }

        //可能是检查员
        if ($system['s']['isweixinxserver'] == 1 && !empty($_P['fromuid']) && !empty($_P['fopenid']) && $_P['scanqr'] != 'yx' && ($_G['ISweixinip'] !== false || $_G['IsFansStatus4']) || intval($_P['fromuid']) < 0) {
            // $_G['openid'] = 'o-IX71QU9mlpZqreSiFoSWTt1234';
            // $_SESSION['oauth_openid'] = 'o-IX71QU9mlpZqreSiFoSWTt1234';

            $temptime = TIMESTAMP - 3;
            $uid = (int)db_fetchcolumn('SELECT COUNT(*) FROM ' . tablename(t_fans) . "
				WHERE themeid = '{$themeid}' and (status =2 or status =4) and addtime<" . $temptime);
            $uid = date("dHi") . $uid;
            $_G['member']['uid'] = -$uid - 1;
            $_G['openid'] = $_G['session_id'];

            $data = array(
                'themeid' => $themeid,
                'uniacid' => $_G['mpid'],
                'uid' => $_G['member']['uid'],
                'openid' => $_G['openid'],
                'nickname' => $_G['IsFansStatus4'] ? "不在活动地区" : "内部测试",
                'avatar' => "",
                'status' => $_G['IsFansStatus4'] ? 4 : 2,
                'ip' => $_G['clientip'],
                'ipaddress' => $_G['address']['province'] . $_G['address']['city'],
                'workerid' => $workerid,
                'addtime' => TIMESTAMP,
            );

            //如果为机器人检查员直接跳过
            $weixinjiqi = ',157.148.40.57,157.148.40.30,157.255.11.80,106.55.202.33,106.55.200.29,106.55.200.24,106.55.202.206,113.96.221.178,58.251.98.105,113.96.219.105,113.96.223.240,113.96.223.239,';
            if (strstr($weixinjiqi, $_G['clientip']) !== false) {
                return $data;
            }

            $fans = db_find("SELECT * FROM " . tablename(t_fans) . "
						WHERE uniacid = '{$_G['mpid']}'  and themeid = '{$themeid}' and openid ='" . $_G['session_id'] . "'");
            if (empty($fans)) {
                $fansid = db_insert(t_fans, $data);
            } else {
                $fansid = $fans['id'];
                $_G['member']['uid'] = $fans['uid'];
            }


            if (!in_array($_P['do'], ['main', 'getbaseyx2020', 'getconfig', 'getbasefcpdd', 'getbasepdd'])) {
                $data = array(
                    'themeid' => $themeid,
                    'uniacid' => $_G['mpid'],
                    'uid' => $_G['member']['uid'],
                    'openid' => $_G['openid'],
                    'nickname' => $_G['url_full'], //.$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'],
                    'avatar' => '',
                    'status' => 1,
                    'addtime' => TIMESTAMP,
                    'fromuid' => $_P['fromuid'],
                    'fopenid' => $_P['fopenid'],
                    'workerid' => $workerid,
                );
                db_insert(t_scan, $data);

                $fans = db_find("SELECT * FROM " . tablename(t_fans) . "
                            WHERE id =" . $fansid);

                $postdata = array(
                    'nickname' => "未授权",
                    'fromuid' => $_P['fromuid'],
                    'ip' => $_G['clientip'],
                );
                $system['themeid'] = $themeid;
                $status = Poster::Getblacklistnew($system, $config, $postdata, $theme['blacklist'], $theme['whitelist']);
            }
            if ($fans['status'] == 4 || $fans['status'] == -5 || stripos($config['whiteiplist'], $_G['clientip']) != false) {
                $fans['status'] = 2;
            }
            return $fans;
        }
//        if ($config['weixinh5'] != 2 && $system['pn_wxapp'] == 0) {
//            if ((stripos($user_agent, 'MicroMessenger') === false || empty($_G['openid']))) {
//                die("<!DOCTYPE html>
//			        <html>
//			            <head>
//			                <meta name='viewport' content='width=device-width, initial-scale=1, user-scalable=0'>
//			                <title>请微信访问{$_G['openid']}</title><meta charset='utf-8'><meta name='viewport' content='width=device-width, initial-scale=1, user-scalable=0'><link rel='stylesheet' type='text/css' href='https://res.wx.qq.com/connect/zh_CN/htmledition/style/wap_err1a9853.css'>
//			            </head>
//			            <body>
//			            <div class='page_msg'><div class='inner'><span class='msg_icon_wrp'><img style='padding:20px; width:200px;' src='{$inputurl}'></span><div class='msg_content'><h4>请在微信客户端打开链接</h4></div></div></div>
//			            </body>
//			        </html>");
//                return;
//            }
//        }
        $_G['member']['uid'] = Fans::getRealUid();
        if ($is_clear_session && $_G['address']['province'] != '广东'
            && strpos($_G['address']['area'], "腾讯") === false
            && $_G['ISweixinip'] == false && !$_G['IsFansStatus4']) {
            $old_url = urlencode($_G['url_full']);
            $clearsession = $_G['url_scheme'] . $_SERVER['HTTP_HOST'] . '/' . createMobileUrl('clearsession', array('themeid' => $themeid, 'recrodid' => $_P['recrodid'], 'fromuid' => $_P['fromuid'], 'fopenid' => $_P['fopenid'], 'workerid' => $_P['workerid'], 'auto' => 'true', 'old_url' => $old_url));
            yxlog($_G['member'], '用户信息缺失');
            echo "<script language='javascript' type='text/javascript'>";
            echo "window.location.href='$clearsession';";
            echo "</script>";
            exit;
        }

        $avatar_default = 'https://css2020.yixuan.net/2020css/yx2020/images/question.png';
        if (!empty($_G['openid'])) {
            $member = member_info($_G['openid']);
            if (empty($member)) {
                $member['avatar'] = $avatar_default;
                $member['nickname'] = '微信用户';
                $member['openid'] = $_G['openid'];
                $member['uid'] = $_G['member']['uid'];

            } else {
                if (!(!empty($member['avatar']) || !empty($member['nickname'])) || !empty($member['updatetime']) && $member['updatetime'] < (time() - 5180000)) {
                    if (!empty($_SESSION['userinfo'])) {
                        unset($_SESSION['userinfo']);
                    }
                    $member['avatar'] = $avatar_default;
                    $member['nickname'] = '微信用户';
                    $member['openid'] = $_G['openid'];
                }
            }
        }
//    	yxlog($member,'h5-member');

        if (empty($_G['openid'])) {
            $_G['openid'] = $member['openid'];
        }
        if (empty($_G['member']['uid'])) {
            $_G['member']['uid'] = member_info($_G['openid']);
        }

        $uid = $_G['member']['uid'];
        $pm = array(":uniacid" => $_G['mpid'], ":themeid" => $themeid, ":openid" => $_G['openid']);
        $fans = db_find("SELECT * FROM " . tablename(t_fans) . "
						WHERE uniacid= :uniacid and themeid = :themeid and openid = :openid", $pm);

        //如果粉丝状态为链接封杀，则更新uid
        if (!empty($fans)) {
            if ($fans['status'] == 5 && !empty($_G['member']['uid'])) {
                db_update(t_fans, array('status' => '1', 'uid' => $_G['member']['uid']), array('uid' => $fans['uid']));
                Fans::updateAlluid($fans['uid'], $_G['member']['uid']);
                $fans['status'] = 1;
                $fans['uid'] = $_G['member']['uid'];
            }
        }
        //如果自动注册员工KEY正确则自动注册员工
        if (!empty($_P['add_worker_key'])) {
            $key = Fans::getAddWorkKey(MODULE_NAME, $theme);
            if ($key == $_P['add_worker_key']) {
                Fans::addworker($theme, $themeid, $_G['member']['uid']);
            }
        }

        if ($system['hdsending'] == 1 && $fans['status'] != 2) {
            $url = $_G['url_full'];
            return return_msg('服务器升级中，请5分钟后重试', $url);
        }

        if ($system['hdget'] == 1 && $_P['send'] == 1 && $fans['status'] != 2) {
            $this->hdget($member, $theme, $system, $theme['softkey']);
            exit;
        }
        if ($system['hdget'] == 1 && $fans['status'] != 2) {
            $this->hdgetnewworkerid($themeid);
        }
        if ($system['hdsend'] == 1 && $system['hdget'] !== 1 && $fans['status'] != 2) {
            $this->hdsend($system['hdsendurl'], $theme['softkey']);
            exit;
        }
        if (empty($fans)) {
            if ($system['hdget'] == 1) {
                //判断新粉丝是否与老用户微信重名，如果重名则打回到原链接进行确认是否支付
                $mcnickname = db_find("SELECT * FROM " . tablename('yx_sys_members') . " WHERE  uid ='" . $_G['member']['uid'] . "'");
                if (!empty($mcnickname['nickname'])) {
                    $fanscm = db_find("SELECT * FROM " . tablename(t_fans) . " WHERE themeid = " . $themeid . "
							  and uid_old is not null and nickname ='" . $mcnickname['nickname'] . "'");
                }
                if (!empty($fanscm['hdsourceurl']) && (!empty($fanscm) || empty($mcnickname['nickname']))) {
                    $this->hdsend($fanscm['hdsourceurl'], $theme['softkey']);
                    exit;
                }
            }
            $this->newfans($member, $theme, $system['hdget']);
            $fans = db_find("SELECT * FROM " . tablename(t_fans) . "
					WHERE uniacid= :uniacid and themeid = :themeid and openid = :openid", $pm);

        } elseif ($_P['do'] != 'getconfig') {
            //检查员第二次访问
            $wxname = explode(",", $system['s']['wxname1'] . "," . $system['s']['wxname2']);
            if ($_G['ISweixinip'] !== false || in_array($member['nickname'], $wxname) || strpos($member['nickname'], "rdgztest") !== false) {
                $postdata = array(
                    'uid' => $_G['member']['uid'],
                    'nickname' => stripcslashes(filterEmoji($member['nickname'])),
                    'avatar' => empty($member['avatar']) ? $member['headimgurl'] : $member['avatar'],
                    'fromuid' => $_P['fromuid'],
                    'ip' => $_G['clientip'],
                );
                $system['themeid'] = $themeid;
                $status = Poster::Getblacklistnew($system, $config, $postdata, $theme['blacklist'], $theme['whitelist']);
                $status = 1;
                if ($status != $fans['status'] && $fans['status'] != 2) {
                    db_query("UPDATE " . tablename(t_fans) . " SET status = " . $status . " WHERE uid = '" . $_G['member']['uid'] . "' and status <> '2'");
                    $fans['status'] = $status;
                }
            }
        }

        if (!empty($fans)) {
            $avatar = empty($member['avatar']) ? $member['headimgurl'] : $member['avatar'];
            $nickname = stripcslashes(filterEmoji($member['nickname']));
            if (($fans['nickname'] == '微信用户' || $fans['nickname'] == '新用户') && !empty($nickname) && $nickname != '微信用户') {
                $update_nickname = true;
            } else {
                $update_nickname = false;
            }
            if ((($fans['avatar'] == $avatar_default || empty($fans['avatar'])) && !empty($avatar)) || $uid != $fans['uid']
                || (empty($fans['mobile']) && !empty($_G['member']['mobile']))
                || $update_nickname
            ) {

                $data = array();
//                if((($fans['avatar'] == $avatar_default || empty($fans['avatar'])) && !empty($avatar)) || $update_nickname){
                if ((($fans['avatar'] == $avatar_default || empty($fans['avatar'])) && !empty($avatar) && $avatar != $avatar_default) || $update_nickname) {
                    $data['nickname'] = $nickname;
                    $data['avatar'] = $avatar;
                    db_update(t_scan, $data, array("openid" => $member['openid']));
                    db_update(t_friend, $data, array("openid" => $member['openid']));
                    db_update(t_relation, $data, array("openid" => $member['openid']));
                    $fans['nickname'] = $nickname;
                    if ($update_nickname) {
                        Common::newfans($system, $theme, $config, $themeid, $fans['status'], $fans);
                    }
                }
                if (empty($fans['mobile']) && !empty($_G['member']['mobile'])) {
                    // $data['username']    = $_G['member']['username'];
                    $data['mobile'] = $_G['member']['mobile'];
                }
                if (!empty($data)) {
                    db_update(t_fans, $data, array("openid" => $member['openid']));
                    db_update(t_worker, $data, array("openid" => $member['openid']));
                    db_update(t_record, $data, array("openid" => $member['openid']));
                    if ($system['fanpai'] == 1) {
                        unset($data['mobile']);
                        db_update(t_fanpaijihui, $data, array("openid" => $member['openid']));
                        db_update(t_fanpaichoujiang, $data, array("openid" => $member['openid']));
                    }
                    //增加重置fromuid\recordid\workerid逻辑
                    if ($update_nickname) {
                        if ($_P['is_wx_oauth'] == 1) {
                            Userdata::addLog($themeid, $_G['member']['uid'], 38);
                        }
                        $reload_arr = Fans::get_now_formuid($themeid);
                        if ($reload_arr['fromuid'] != $_P['fromuid'] || $reload_arr['recordid'] != $_P['recordid'] || $reload_arr['workerid'] != $_P['workerid']) {
//                            $url = urldecode($_SESSION['dest_url']);
//                            $url .= "&fopenid=" . $reload_fopenid . "&fromuid=".$reload_fromuid ."&workerid=".$reload_workerid;
                            $url_data = $_P;
                            $url_data['fopenid'] = $reload_arr['fopenid'];
                            $url_data['fromuid'] = $reload_arr['fromuid'];
                            $url_data['workerid'] = $reload_arr['workerid'];
                            $url = createMobileUrl($_P['do'], $url_data, true);
                            echo "<script language='javascript' type='text/javascript'>";
                            echo "window.location.href='$url';";
                            echo "</script>";
                            exit;
                        }
                    }
                }

                $fans = db_find("SELECT * FROM " . tablename(t_fans) . "
                            WHERE uniacid= :uniacid and themeid = :themeid and openid = :openid", $pm);
            }
        }

        if ($system['hdsend'] == 1 && $fans['status'] != 2) {
            $this->hdsend($system['hdsendurl'], $theme['softkey']);
            exit;
        }
        if ($fans['status'] == 4 || $fans['status'] == -5 || stripos($config['whiteiplist'], $_G['clientip']) != false) {
            $fans['status'] = 2;
        }
        //扫描原始码
        if ((empty($_P['fromuid']) && empty($_P['fopenid']) || $_P['scanqr'] == 'yx') && $_P['do'] != 'w_init' && $_P['do'] != 'x_init') {
            if ($fans['status'] < 1 && !empty($fans)) {
                $fans['status'] = 3;
                yxlog("扫原始码进入白名单:UID:" . $fans['uid'] . "昵称:" . $fans['nickname'], '粉丝操作');
                db_update(t_fans, array('status' => 3), array("uid" => $fans['uid']));
            }
        }
        if ($fans['status'] < 1 && !empty($fans)) {
            if ($config['weixinh5'] != 2) {
                if ($fans['status'] == 0 || $fans['status'] == -4) {
                    echo "<script language='javascript' type='text/javascript'>";
                    echo "window.location.href='" . $system['s']['errorpage'] . "?ip=" . $_G['clientip'] . "&fans=" . $fans['uid'] . "';";
                    echo "</script>";
                    exit;
                }
                if ($fans['status'] < 0) {
                    echo "<script language='javascript' type='text/javascript'>";
                    echo "window.location.href='" . $system['s']['lockpage'] . "?ip=" . $_G['clientip'] . "&fans=" . $fans['uid'] . "';";
                    echo "</script>";
                    exit;
                }

//                echo "<link href=\"".$_G['URL']['LAYER_CSS']."css/layui.css\" rel=\"stylesheet\">";
//                echo "<script src=\"".$_G['URL']['LAYER_CSS']."layui.all.js\"></script>";
//                echo "<script language='javascript' type='text/javascript'>";
//                echo "layer.confirm('错误代码：'".$fans['uid'].",{btn:['访问出错'],closeBtn:0},function(){";
//                echo "window.location.href='" . $system['s']['lockpage'] . "';";;
//                echo "})";
//                echo "</script>";
//                exit;
            }
        }
        if ($fans['status'] == 1) {
            $fans['status'] = Poster::GetSoftblacklist($theme['blacklist'], $fans['nickname'], $fans['uid']);
        }

        return $fans;
    }

    //入口参数
    protected function Isworker($isworker = true)
    {
        global $_P, $_G;
        $fans = $this->checkuser();
        if (empty($fans['uid']) || empty($_G['openid'])) {
            return return_msg('用户未授权无法访问，请从首页重新进入');
            exit;
        }
        $system = $_G['system'];
        $themeid = intval($_P['themeid']);
        $theme = Theme::getThemeById($themeid);

        if (empty($theme['id'])) {
            return return_msg('活动入口不正确');
            exit;
        }
        if ($isworker && empty($theme['softsn'])) {
            return return_msg('软件未激活,请联系' . $_G['companyname'] . '工作人员');
            exit;
        }
        if ($isworker && $theme['softsn_status'] == 1) {
            return return_msg('版面待确认,请联系' . $_G['companyname'] . '工作人员');
            exit;
        }
        if ($isworker) {
            $msg = Worker::gethoutaistats();
        }
        if (!empty($msg) && strtolower($_P['do']) != 'myorderworkercheck') {
            return return_msg($msg);
        }
        $config = Theme::getConfig($themeid);
        $myworker = Worker::getThemeWorkerByOpenidNew($_G['openid'], $themeid);
        // var_dump($myworker);
        if (!(!$system['is_multiple_merchants'] || $config['showshop'] == 0 || ($system['is_multiple_merchants'] && $config['showshop'] == $myworker['company']))) {
            $myworker = "";
        }
        if ($isworker && (empty($myworker) || $myworker['level'] > 3)) {
            return return_msg('您不是员工,无权访问');
            exit;
        }

        $jubf['title'] = empty($theme['jubf']) ? '' : $theme['jubf'] . '-';
        $jubf['banquan'] = !empty($theme['USERCOMPANYNAME']) ? $theme['USERCOMPANYNAME'] : $_G['companyname'];

        $result = array(
            'system' => $system,
            'theme' => $theme,
            'config' => $config,
            'fans' => $fans,
            'themeid' => $themeid,
            'myworker' => $myworker,
            'jubf' => $jubf,
            'jishu' => Worker::getjishu($theme, $system),
        );
        return $result;
    }

    protected function newfans($member, $theme, $hdget)
    {
        global $_G, $_P;
        if (empty($_G['openid'])) {
            $_G['openid'] = $member['openid'];
            $_G['member']['uid'] = $member['uid'];
        }
        $_G['member']['uid'] = Fans::getRealUid();
        if (empty($_G['openid']) || empty($_G['member']['uid'])) {
            return;
        }
        $system = $_G['system'];
        $themeid = intval($_P['themeid']);
        $config = Theme::getConfig($themeid);

        $workerid = intval($_P['workerid']);
        $fromuid = intval($_P['fromuid']);
        $fopenid = $_P['fopenid'];
        if ($fromuid == $_G['member']['uid'] || $fopenid == $_G['openid']) {
            $fromuid = 0;
            $fopenid = "";
        } elseif ($workerid > 0 && $fromuid == 0) {
            $theyworker = Worker::getThemeWorkerByUid($workerid, $themeid, 1);
            $fromuid = $theyworker['uid'];
            $fopenid = $theyworker['openid'];
        }
        if ($workerid == 0 && $fromuid > 0) {//有推荐人无员工
            $workerid = Fans::get_now_formuid($themeid, $fromuid)['workerid'];
        }
        if ($fromuid > 0) {//判断推荐者是不是员工
            $isworker = Worker::getThemeWorkerByUid($fromuid, $themeid, 1);
            if (!empty($isworker)) {
                $workerid = $isworker['uid'];
            }
        }

        $pm = array(":themeid" => $themeid, ":openid" => $_G['openid']);
        $fans = db_find("SELECT * FROM " . tablename(t_fans) . "
						WHERE themeid = :themeid and openid = :openid", $pm);
        if (empty($fans)) {
            $postdata = array(
                'uid' => $_G['member']['uid'],
                'nickname' => stripcslashes(filterEmoji($member['nickname'])),
                'avatar' => empty($member['avatar']) ? $member['headimgurl'] : $member['avatar'],
                'fromuid' => $_P['fromuid'],
                'ip' => $_G['clientip'],
            );
            $system['themeid'] = $themeid;
            $status = Poster::Getblacklistnew($system, $config, $postdata, $theme['blacklist'], $theme['whitelist']);
            $status = 1;
            $data = array(
                'themeid' => $themeid,
                'uniacid' => $_G['mpid'],
                'uid' => $_G['member']['uid'],
                'openid' => $_G['openid'],
                'nickname' => stripcslashes(filterEmoji($member['nickname'])),
                'avatar' => empty($member['avatar']) ? $member['headimgurl'] : $member['avatar'],
                'status' => $status,
                'ip' => $_G['clientip'],
                'ipaddress' => $_G['address']['province'] . $_G['address']['city'],
                'workerid' => $workerid,
                'addtime' => TIMESTAMP,
            );
            if ($hdget == 1 && Fans::getuid_old($workerid, $themeid)) {
                $data['workerid_old'] = $workerid;
            }

            if (!empty($data['nickname']) || !empty($data['avatar'])) {
                //判断IP是否在白名单，如果在修改fans而非添加
                if (stripos($config['whiteiplist'], $_G['clientip']) !== false) {
                    $fanssession = db_find("SELECT * FROM " . tablename(t_fans) . "
                            WHERE uniacid = '{$_G['mpid']}'  and themeid = '{$themeid}' and openid ='" . $_G['session_id'] . "'");
                    if (empty($fanssession)) {
                        db_insert(t_fans, $data);
                    } else {
                        db_update(t_fans, $data, array('id' => $fanssession['id']));
                    }
                } else {
                    db_insert(t_fans, $data);
                }
            }
            $fans = $data;


            $p = array(":uniacid" => $_G['mpid'], ":themeid" => $themeid);
            db_query("UPDATE " . tablename(t_theme) . " SET fanscount = fanscount +1 WHERE uniacid = :uniacid and id =:themeid", $p);

            $p = array(":uniacid" => $_G['mpid'], ":themeid" => $themeid);
            db_query("UPDATE " . tablename(t_report) . " SET newfans = newfans +1 WHERE software = '" . MODULE_NAME . "' and uniacid = :uniacid and themeid =:themeid and riqi ='" . date("Y-m-d") . "'", $p);
            Theme::workerreport($themeid, $workerid, array('newfans' => 1));


            //限制地区访问
            if (!empty($config['viewcity']) && $status == 1) {
                $ClientIp = $_G['clientip'];
                $viewresult = Comm::getCity($system, $ClientIp, $config['viewcity']);
                if ($viewresult['status'] == 0) {
                    $whitestate = 0;
                    if (!empty($config['viewcitywhitelist'])) {
                        $softwhitelist = str_replace(",", "|", $config['viewcitywhitelist']);
                        $nickname = $member['nickname'];
                        $whitelist = explode("|", "|" . $softwhitelist);

                        foreach ($whitelist as $key => $row) {
                            if (!empty($row)) {
                                if (strstr($nickname, $row) !== false) {
                                    $whitestate = 1;
                                }
                            }
                        }
                    }
                    if ($whitestate == 0) {
                        db_query("UPDATE " . tablename(t_fans) . " SET status = 0 WHERE uid = '" . $_G['member']['uid'] . "' and status <> '2'");
                        $status = 0;
                    }
                }
            }
            if ($fans['nickname'] != '微信用户' && $fans['nickname'] != '新用户' || $config['comm5UserLimit'] == 1) {
                Common::newfans($system, $theme, $config, $themeid, $status, $fans);
            }
        }
        $sacn = Scan::getByThemeIduid($themeid, $_G['member']['uid']);
        if (empty($sacn)) {
            $data = array(
                'themeid' => $themeid,
                'uniacid' => $_G['mpid'],
                'uid' => $_G['member']['uid'],
                'openid' => $_G['openid'],
                'nickname' => stripcslashes(filterEmoji($member['nickname'])),
                'avatar' => empty($member['avatar']) ? $member['headimgurl'] : $member['avatar'],
                'status' => 0,
                'addtime' => TIMESTAMP,
                'fromuid' => $fromuid,
                'fopenid' => $fopenid,
                'workerid' => $workerid,
            );
            if ($system['hdget'] == 1) {
                if (Fans::getuid_old($fromuid, $themeid)) {
                    $data['fromuid_old'] = $fromuid;
                    $data['fopenid_old'] = $fopenid;
                }
                if (Fans::getuid_old($workerid, $themeid)) {
                    $data['workerid_old'] = $workerid;
                }
            }
            if ($config['iconlimit'] > 0) {
                $todaynum = Scan::getFpenidTodayNum($themeid, $fopenid);
                if ($todaynum < $config['iconlimit']) {
                    $data['status'] = 1;
                }
            } else {
                $data['status'] = 1;
            }
            db_insert(t_scan, $data);
            if (!empty($fromuid)) {
                db_query("UPDATE " . tablename(t_fans) . " SET responsum = responsum + 1 WHERE themeid = '{$themeid}' and uid ={$fromuid}");
            }
        }
        if ($_P['do'] == 'index' && ($_G['member']['uid'] != $_P['fromuid'] || $_P['fx'] != 1)) {
            if ($fromuid > 0 && !empty($fopenid)) {
                $relation = Relation::getByThemeId($themeid, $_G['openid']);
                $data = array(
                    'themeid' => $themeid,
                    'uniacid' => $_G['mpid'],
                    'uid' => $_G['member']['uid'],
                    'openid' => $_G['openid'],
                    'status' => 1,
                    'addtime' => TIMESTAMP,
                    'parentid' => $fromuid,
                    'popenid' => $fopenid,
                );
                if ($system['hdget'] == 1 && Fans::getuid_old($fromuid, $themeid)) {
                    $data['parentid_old'] = $fromuid;
                    $data['popenid_old'] = $fopenid;
                }
                if (empty($relation)) {
                    if ($system['hdget'] == 1 && Fans::getuid_old($workerid, $themeid)) {
                        $data['workerid_old'] = $workerid;
                    }
                    $data['workerid'] = $workerid;
                    db_insert(t_relation, $data);
                } elseif ($relation['isorder'] != 1) {//如果没有付款则更新上下关系

                    if ($relation['popenid'] != $fopenid && $relation['isfrozen'] != 1) {
                        Relation::update($relation['id'], $data);
                    }
                    if ($relation['workerid'] != $workerid && $workerid > 0) {
                        if ($system['hdget'] == 1 && Fans::getuid_old($workerid, $themeid)) {
                            Relation::update($relation['id'], array('workerid' => $workerid, 'workerid_old' => $workerid));
                        } else {
                            Relation::update($relation['id'], array('workerid' => $workerid));
                        }
                    }
                }
            }
        }
    }

    protected function hdgetnewworkerid($themeid)
    {
        global $_G, $_P;
        //员工信息为老的，且员工信息已更新，则跳转为新信息
        if (!empty($_P['workerid'])) {
            $workerid_list = db_find("SELECT * FROM " . tablename(t_worker) . " WHERE themeid = " . $themeid . " and uid_old = " . $_P['workerid']);
            if (!empty($workerid_list) && $workerid_list['uid'] !== $workerid_list['uid_old']) {
                $url = $_G['url_scheme'] . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?' . str_replace("&workerid=" . $_P['workerid'], "&workerid=" . $workerid_list['uid'], $_SERVER['QUERY_STRING']);
                echo "<script language='javascript' type='text/javascript'>";
                echo "window.location.href='$url';";
                echo "</script>";
                exit;
            }
        }
        //来源信息为老的，且来源信息已更新则跳转为新信息
        if (!empty($_P['fopenid'])) {
            $workerid_list = db_find("SELECT * FROM " . tablename(t_fans) . " WHERE themeid = " . $themeid . " and openid_old = '" . $_P['fopenid'] . "'");
            if (!empty($workerid_list) && $workerid_list['uid'] !== $workerid_list['uid_old']) {
                $url = str_replace("&fromuid=" . $_P['fromuid'], "&fromuid=" . $workerid_list['uid'], $_SERVER['QUERY_STRING']);
                $url = str_replace("&fopenid=" . $_P['fopenid'], "&fopenid=" . $workerid_list['openid'], $$url);
                $url = $_G['url_scheme'] . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?' . $url;
                echo "<script language='javascript' type='text/javascript'>";
                echo "window.location.href='$url';";
                echo "</script>";
                exit;
            }
        }
    }

    protected function hdget($member, $theme, $system, $softkey)
    {
        global $_G, $_P;
        $hdget = $system['hdget'];
        $themeid = $_P['themeid'];
        $fans = db_find("SELECT * FROM " . tablename(t_fans) . " WHERE themeid = " . $themeid . " and uid_old = " . $_P['uid']);
        if (!empty($fans)) {
            if ($fans['uid'] == $fans['uid_old']) {
                if ($system['hdsend'] == 1) {
                    //若开启了再次跳转，没有更新信息，则直接跳转
                    $data = array(
                        'do' => $_P['do'],
                        'themeid' => $_P['themeid'],
                        'uid' => $_P['uid'],
                        'openid' => $_P['openid'],
                        'workerid' => $_P['workerid'],
                        'recordid' => $_P['recordid'],
                        'fromuid' => $_P['fromuid'],
                        'fopenid' => $_P['fopenid'],
                        'help_uid' => $_P['help_uid'],
                        'op' => $_P['op'],
                        'isfans' => $_P['isfans'],
                    );
                    $url = $system['hdsendurl'] . "&send=1&soft=" . $softkey;
                    foreach (array_keys($data) as $index => $key) {
                        if (!empty($data[$key])) {
                            $url = $url . "&" . $key . "=" . $data[$key];
                        }
                    }
                    echo "<script language='javascript' type='text/javascript'>";
                    echo "window.location.href='" . $url . "';";
                    echo "</script>";
                    exit;
                } else {
                    $this->hd_renew('fans', 'uid,openid,fromuid,fopenid,workerid');
                    $this->hd_renew('code', 'uid,openid');
                    $this->hd_renew('comm', 'uid,openid,fromuid,fopenid,workerid');
                    $this->hd_renew('commshare', 'uid,openid');
                    $this->hd_renew('exchange', 'uid,openid,workerid');
                    $this->hd_renew('fanpaichoujiang', 'uid,openid,workerid');
                    $this->hd_renew('fanpaijihui', 'uid,openid,fromuid,fopenid,workerid');
                    $this->hd_renew('friend', 'uid,openid,fromuid,fopenid,workerid');
                    $this->hd_renew('hexiao', 'uid,workerid');
                    $this->hd_renew('order', 'uid,openid,workerid');
                    $this->hd_renew('record', 'uid,openid,fromuid,fopenid,workerid');
                    $this->hd_renew('relation', 'uid,openid,parentid,popenid,workerid');
                    $this->hd_renew('scan', 'uid,openid,fromuid,fopenid,workerid');
                    $this->hd_renew('share', 'uid,openid,fromuid,fopenid,workerid');
                    $this->hd_renew('worker', 'uid,openid');
                    $this->hd_renew('workerreport', 'workerid');
                }
            }
        } else {
            $this->newfans($member, $theme, $hdget);
        }
        if (!empty($_P['workerid'])) {
            $workerid_list = db_find("SELECT * FROM " . tablename(t_worker) . " WHERE themeid = " . $themeid . " and uid_old = " . $_P['workerid']);
            $workerid = $workerid_list['uid'];

        }
        if (!empty($_P['fopenid'])) {
            $fromuid_list = db_find("SELECT * FROM " . tablename(t_fans) . " WHERE themeid = " . $themeid . " and openid_old = '" . $_P['fopenid'] . "'");
            $fromuid = $fromuid_list['uid'];
            $fopenid = $fromuid_list['openid'];
        }
        if (!empty($_P['help_uid'])) {
            $fromuid_list = db_find("SELECT * FROM " . tablename(t_fans) . " WHERE themeid = " . $themeid . " and uid_old = " . $_P['help_uid']);
            $help_uid = $fromuid_list['uid'];
        }
        $data = array(
            'do' => $_P['do'],
            'themeid' => $_P['themeid'],
            'uid' => $_G['member']['uid'],
            'openid' => $_G['openid'],
            'recordid' => $_P['recordid'],
            'op' => $_P['op'],
            'workerid' => $workerid,
            'fromuid' => $fromuid,
            'fopenid' => $fopenid,
            'help_uid' => $help_uid,
        );
        $url = $_G['siteroot'] . "app/index.php?i=" . $_G['mpid'] . "&c=entry&m=" . MODULE_NAME;
        $url = $url . "&soft=" . $_P['soft'];

        foreach (array_keys($data) as $index => $key) {
            if (!empty($data[$key])) {
                $url = $url . "&" . $key . "=" . $data[$key];
            }
        }
        echo "<script language='javascript' type='text/javascript'>";
        echo "window.location.href='" . $url . "';";
        echo "</script>";
        exit;
    }

    protected function hd_renew($tablename, $fieldnames)
    {
        global $_G, $_P;
        $tablename = MODULE_NAME . "_a" . $tablename;
        $uid = $_G['member']['uid'];
        $openid = $_G['openid'];

        $fieldname = explode(",", $fieldnames);
        foreach ($fieldname as $key => $row) {
            if ($row == 'workerid' || $row == 'uid' || $row == 'fromuid' || $row == 'parentid') {
                db_update($tablename, array($row => $uid), array($row . '_old' => $_P['uid']));
            } else {
                db_update($tablename, array($row => $openid), array($row . '_old' => $_P['openid']));
            }
        }
        if ($tablename == 'comm') {
            db_update($tablename, array('msg' => ''), array('uid_old' => $_P['uid'], 'msg' => '-2:openid与商户appid不匹配'));
        }
    }


    protected function hdsend($hdsendurl, $softkey)
    {
        global $_G, $_P;
        $themeid = $_P['themeid'];
        $isfans = db_find("SELECT * FROM " . tablename(t_fans) . "
						WHERE uniacid= " . $_G['mpid'] . " and themeid = " . $themeid . " and uid = '" . $_G['member']['uid'] . "'");
        $data = array(
            'do' => $_P['do'],
            'themeid' => $_P['themeid'],
            'uid' => $_G['member']['uid'],
            'openid' => $_G['openid'],
            'workerid' => $_P['workerid'],
            'recordid' => $_P['recordid'],
            'fromuid' => $_P['fromuid'],
            'fopenid' => $_P['fopenid'],
            'help_uid' => $_P['help_uid'],
            'op' => $_P['op'],
            'isfans' => !empty($isfans),
        );
        $url = $hdsendurl . "&send=1&soft=" . $softkey;
        foreach (array_keys($data) as $index => $key) {
            if (!empty($data[$key])) {
                $url = $url . "&" . $key . "=" . $data[$key];
            }
        }
        echo "<script language='javascript' type='text/javascript'>";
        echo "window.location.href='" . $url . "';";
        echo "</script>";
        exit;
    }

    protected function getsystem()
    {
        global $_G;
        return $_G['system'];
    }

    protected function getJsSdkConfig($url = '', $debug = false)
    {
        $js_sdk_config = WxoffiAccount::getInstance()->getJsConfig($url);
        $format_js_sdk_config = json_encode($js_sdk_config);
        $debug = $debug ? 'true' : 'false';
        $script = <<<EOF

<script src="https://res.wx.qq.com/open/js/jweixin-1.3.2.js"></script>
<script type="text/javascript">

	// jssdk config 对象
	jssdkconfig = $format_js_sdk_config;

	// 是否启用调试
	jssdkconfig.debug = $debug;

	jssdkconfig.jsApiList = [
		'checkJsApi',
		'onMenuShareTimeline',
		'onMenuShareAppMessage',
		'onMenuShareQQ',
		'onMenuShareWeibo',
		'hideMenuItems',
		'showMenuItems',
		'hideAllNonBaseMenuItem',
		'showAllNonBaseMenuItem',
		'translateVoice',
		'startRecord',
		'stopRecord',
		'onRecordEnd',
		'playVoice',
		'pauseVoice',
		'stopVoice',
		'uploadVoice',
		'downloadVoice',
		'chooseImage',
		'previewImage',
		'uploadImage',
		'downloadImage',
		'getNetworkType',
		'openLocation',
		'getLocation',
		'hideOptionMenu',
		'showOptionMenu',
		'closeWindow',
		'scanQRCode',
		'chooseWXPay',
		'openProductSpecificView',
		'addCard',
		'chooseCard',
		'openCard'
	];

	wx.config(jssdkconfig);

</script>
EOF;
        return $script;
    }
}